
package cn.ckx.coding.advice;


import cn.ckx.coding.common.dto.ApiResponse;
import cn.ckx.coding.common.exception.BusinessException;
import cn.ckx.coding.common.exception.ErrorCodes;
import cn.hutool.json.JSONObject;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Map;

/**
 * @author kunxin.cai 
 */
@RestControllerAdvice
@Slf4j
public class ExceptionHandlerAdvice {
    
    @ExceptionHandler(BusinessException.class)
    public ApiResponse handler(BusinessException e) {
        return ApiResponse.error(e.getCode(), e.getMessage()).of(e.getData());
    }

    @ExceptionHandler(Exception.class)
    public ApiResponse handlerException(Exception e) {
        log.error("未知异常，异常类型 : {}，异常消息 : {} ,异常地址 : {}",e.getClass(),e.getMessage(),e.getStackTrace());
        return ApiResponse.error(ErrorCodes.UNEXPECT_ERROR, "系统繁忙，请稍后再试");
    }

    @ExceptionHandler(Throwable.class)
    public ApiResponse handlerThrowable(Throwable throwable) {
        log.error("未知异常，异常类型 : {}，异常消息 : {} ,异常地址 : {}",throwable.getClass(),throwable.getMessage(),throwable.getStackTrace());
        return ApiResponse.error(ErrorCodes.UNEXPECT_ERROR, "系统繁忙，请稍后再试");
    }

    @ExceptionHandler(value = {BindException.class, MethodArgumentNotValidException.class})
    public ApiResponse handlerBindException(Exception e){
        BindingResult bindingResult = new JSONObject(e).getJSONObject("bindingResult").toBean(BindingResult.class);
        Map<String,String> errorMap = Maps.newHashMap();
        bindingResult.getFieldErrors().forEach((fieldError) -> errorMap.put(fieldError.getField(), fieldError.getDefaultMessage()));
        return ApiResponse.error(ErrorCodes.BAD_REQUEST, e.getMessage()).of(errorMap);
    }

    @ExceptionHandler(value = {DuplicateKeyException.class})
    public ApiResponse handlerSqlIntegrityConstraintViolationException(DuplicateKeyException e){
        SQLIntegrityConstraintViolationException exception = (SQLIntegrityConstraintViolationException)(e.getCause());
        int errorCode = exception.getErrorCode();
        return ApiResponse.error(ErrorCodes.PARAMETER_MISS, String.format("该参数已存在：%d",errorCode));
    }  

}
